package controller;

import entity.Good;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/Sum")
public class Sum extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        double price = 0;
        int number = 0;
        boolean wrong = false;
        try {
            price = Double.parseDouble(request.getParameter("price"));
            number = Integer.parseInt(request.getParameter("number"));
        } catch (NumberFormatException e) {
            out.println("<h1>格式错误</h1>");
            wrong=true;
        }

        if(price<0||number<0){
            out.println("<h1>不能为负数</h1>");
            price=0;number=0;
            wrong=true;
        }

        Good good = new Good(price,number);

        if(wrong==false){
            out.println("<h1>总价为" + good.calcsum() + "</h1>");
        }else if(wrong==true){
            out.println("<h1>不能计算总价</h1>");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
